package com.ruoyi.framework.dataPermission;

import com.ruoyi.common.annotation.DataPermission;

import java.util.ArrayDeque;
import java.util.Deque;


public class DataPermissionHolder {

    private static final ThreadLocal<Deque<Object>> TL = ThreadLocal.withInitial(ArrayDeque::new);

    private static final Object NULL = new Object();

    public static DataPermission getDataPermission(){
        Deque<?> stack = TL.get();
        if (stack.isEmpty()) {
            return null;
        }
        Object obj = stack.getLast();
        if (obj == NULL) {
            return null;
        }
        return (DataPermission) obj;
    }

    public static void setDataPermission(DataPermission dataPermission){
        if (dataPermission == null) {
            TL.get().addLast(NULL);
        } else {
            TL.get().addLast(dataPermission);
        }
    }

    public static void removeDataPermission(){
        TL.get().removeLast();
    }

    public static void withIgnore(Runnable call){
        try{
            setDataPermission(null);
            call.run();
        }finally {
            removeDataPermission();
        }
    }

}
